from waveapi import events
from waveapi import model
from waveapi import robot
from waveapi import document
from waveapi import robot_abstract
from waveapi import simplejson as json

import string
import logging

def AddGadget(properties, context):

    root_wavelet = context.GetRootWavelet()
    root_blip = context.GetBlipById(root_wavelet.GetRootBlipId()) 
    wavetype = string.lower(root_blip.GetDocument().GetText()[0])

    if wavetype == 'a':
        waveid = context.GetWaves()[0].GetId()

        gadget_arguments = {'waveid' : waveid}
        gadget_address = 'http://pgch.co.uk/gadgets/debatewise.Admin.xml'
        debatewise_gadget = document.Gadget(gadget_address, gadget_arguments)

        root_blip.GetDocument().AppendElement(debatewise_gadget)

def GadgetEventHandler(properties, context):

    # get the data from the current wave and its resident gadget
    root_wavelet = context.GetRootWavelet()
    root_blip = context.GetBlipById(root_wavelet.GetRootBlipId())   

    debatewise_gadget = None
    try:
        debatewise_gadget = [x for x in root_blip.GetElements().values() if x.type == document.ELEMENT_TYPE.GADGET][0] 
    except:
        logging.debug('Failed to find the resident gadget. This should not generally happen.')

    # make sure we are responding to a legitimate event, not some other blip changes
    if int(debatewise_gadget.get('requesttype', '0')) == 1:
        gadget_addresses = ['http://pgch.co.uk/gadgets/debatewise.Admin.xml',
                            'http://pgch.co.uk/gadgets/debatewise.Index.xml',
                            'http://pgch.co.uk/gadgets/debatewise.Debate.xml',
                            'http://pgch.co.uk/gadgets/debatewise.Point.xml']
        gadget_address = debatewise_gadget.get('url')
        new_gadget_address = gadget_addresses[gadget_addresses.index(gadget_address) + 1]
        
        new_wave_titles = ["Admin Gadget",
                           "Debatewise: Index of debates",
                           "Debatewise: Debate",
                           "Debatewise: Point"]
        new_wave_title = new_wave_titles[gadget_addresses.index(gadget_address) + 1]
        
        new_content_id = debatewise_gadget.get('nextcontentid')
        participants = debatewise_gadget.get('participants').split(',')

        bot_address = 'aleksei-testbot@appspot.com' 
        participants.append(bot_address)

        waveid = context.GetWaves()[0].GetId()
    
        # create a wave
        new_wave = robot_abstract.NewWave(context, participants)
        new_wave.SetTitle(new_wave_title)
        new_wave_id = new_wave.GetWaveId()

        logging.debug(waveid)
        logging.debug(new_wave_id)

        # add a gadget to the new wave
        gadget_arguments = {'waveid' : new_wave_id, 'contentid' : new_content_id}
        new_gadget = document.Gadget(new_gadget_address, gadget_arguments)

        new_root_blip = context.GetBlipById(new_wave.GetRootBlipId())
        new_root_blip.GetDocument().AppendElement(new_gadget)

        # return the new waveId to the current gadget
        debatewise_gadget.SubmitDelta({'nextwaveid' : new_wave_id})
        debatewise_gadget.SubmitDelta({'requesttype' : 0})

    elif int(debatewise_gadget.get('requesttype', '0')) == 2:  
        waveid = context.GetWaves()[0].GetId()
        root_wavelet = context.GetRootWavelet()

        new_participant_sets_count = int(debatewise_gadget.get('participantssetscount', '0'))
        if new_participant_sets_count > 0:
            new_participants_sets_json = debatewise_gadget.get('participantssetsjson', '')

            for participant_set in json.loads(new_participants_sets_json):
                if waveid == participant_set['waveid']:
                    for participant in participant_set['participants'].split(','):
                        root_wavelet.AddParticipant(participant)
            
            debatewise_gadget.SubmitDelta({'requesttype' : 0})

if __name__ == '__main__':
    debatewise_robot = robot.Robot('aleksei-testbot',
        image_url='http://aleksei-testbot.appspot.com/assets/icon.png',
        version='7',
        profile_url='http://aleksei-testbot.appspot.com/')

    debatewise_robot.RegisterHandler(events.WAVELET_SELF_ADDED, AddGadget)
    debatewise_robot.RegisterHandler(events.BLIP_SUBMITTED, GadgetEventHandler)

    debatewise_robot.Run()
